package com.hmall.trade.listener;

import com.hmall.trade.domain.po.Order;
import com.hmall.trade.enums.OrderStatus;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author ChenPi
 * @since 2025/03/06 09:04
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PayStatusListener {

    private final IOrderService orderService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "trade.pay.success.queue", durable = "true"),
            exchange = @Exchange(name = "pay.direct", type = ExchangeTypes.DIRECT),
            key = "pay.success"
    ))
    public void listenPaySuccess(Long orderId) {
        log.info("支付状态发生变化，支付单id:{}", orderId);

        // 业务幂等
        // 查询支付单
        Order order = orderService.getById(orderId);
        if (order == null || order.getStatus() != OrderStatus.UNPAID) {
            log.error("支付单不存在，支付单id:{}", orderId);
            return;
        }

        orderService.markOrderPaySuccess(orderId);
    }
}
